package cn.graydove.bot.core;

import cn.graydove.bot.annotation.Listener;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;

import java.lang.reflect.Method;

@Configuration
public class SpringBeanProcessor implements BeanPostProcessor, ApplicationContextAware {

    private ProcessorManager processorManager;

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> clazz = bean.getClass();

        Method[] methods = clazz.getMethods();
        for (Method method: methods) {
            Listener listener = AnnotationUtils.findAnnotation(method, Listener.class);
            if (listener != null) {
                processorManager.register(new Function(method, bean, listener.value()));
            }
        }

        if (bean instanceof Processor) {
            processorManager.registerProcessor((Processor) bean);
        }
        return null;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        processorManager = applicationContext.getBean(ProcessorManager.class);
    }
}
